package com.jiaquyun.jcyx.main.goods

import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.GsonUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.CartAction
import com.jiaquyun.jcyx.entity.GoodsActivity
import com.jiaquyun.jcyx.entity.GoodsGroup
import com.jiaquyun.jcyx.main.goods.adapter.GoodsHomeAdapter
import com.jiaquyun.jcyx.jetpack.mode.CartViewModel
import com.jiaquyun.jcyx.utils.JsonUtils
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_goods_home.*

class GoodsHomeFragment : OwnerViewModeFragment<CartViewModel>() {

    private val goodsHomeAdapter: GoodsHomeAdapter =
        GoodsHomeAdapter()

    companion object {
        private const val KEY_GOODS_ACTIVITY = "KEY_GOODS_ACTIVITY"
        fun newInstance(goodsActivity: GoodsActivity?): GoodsHomeFragment {
            val bundle: Bundle = Bundle().apply {
                putSerializable(KEY_GOODS_ACTIVITY, goodsActivity)
            }
            return GoodsHomeFragment().apply {
                arguments = bundle
            }
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_goods_home

    override fun viewModel(): CartViewModel {
        return createViewModel()
    }

    override fun initView() {
        rvGoodsHomeBody.apply {
            itemAnimator?.changeDuration = 0
        }.adapter = goodsHomeAdapter.apply {

            val goodsActivity: GoodsActivity? =
                arguments?.getSerializable(KEY_GOODS_ACTIVITY) as? GoodsActivity
            if (goodsActivity != null)
                setEmptyView(createLoadingView())
        }
        goodsHomeAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: GoodsGroup = goodsHomeAdapter.getItem(position)
            if (view.id == R.id.ivGoodsPlus) {
                val num: Int = itemData.cart_num + 1
                if (itemData.cart_id == 0 || itemData.cart_num == 0) {
                    viewModel.cartAdd1(itemData.id, num)
                } else {
                    viewModel.cartChangeNum1(itemData.id, itemData.cart_id, num)
                }
            }
            if (view.id == R.id.ivGoodsMinus) {
                val num: Int = itemData.cart_num - 1
                if (num == 0) {
                    viewModel.cartRemove(itemData.id, itemData.cart_id)
                } else {
                    viewModel.cartChangeNum1(itemData.id, itemData.cart_id, num)
                }
            }
        }
    }

    override fun initData() {
        val goodsActivity: GoodsActivity =
            arguments?.getSerializable(KEY_GOODS_ACTIVITY) as? GoodsActivity
                ?: return
        val goodsGroups:MutableList<GoodsGroup> = try {
            JsonUtils.stringToList(goodsActivity.goods_group,GoodsGroup::class.java)
        }catch (e:Exception) {
            mutableListOf<GoodsGroup>()
        }
        goodsHomeAdapter.setNewInstance(goodsGroups)
        if (goodsGroups.isNullOrEmpty()) {
            goodsHomeAdapter.removeEmptyView()
        } else {
            goodsHomeAdapter.setFooterView(createFooterView().apply {
                setOnClickListener {
                    val data = GoodsActiveActivity.GoodsActiveValue(
                        goodsActivity.id, goodsActivity.title, goodsActivity.image
                    )
                    GoodsActiveActivity.open(requireActivity(), data)
                }
            })
        }
    }

    override fun initViewMode() {


        //监听购物车添加
        viewModel.cartAdd1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNum1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车删除
        viewModel.cartDelete1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.status.desc)
            }
        })
    }


    override fun onEventMainThread(any: Any) {
        if (any !is CartAction)
            return
        if (any.action == CartAction.Action.CLEAR) {
            val position = mutableListOf<Int>()
            for ((index, item) in goodsHomeAdapter.data.withIndex()) {
                if (item.cart_num != 0) position.add(index)
            }
            position.forEach {
                goodsHomeAdapter.setData(it)
            }
        } else {
            val position = goodsHomeAdapter.data.indexOfFirst {
                it.id == any.goodsId
            }
            if (position == -1)
                return
            goodsHomeAdapter.setData(position, any.goodsNum, any.cartId)
        }
    }

    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createFooterView(): View = TextView(requireContext()).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            ConvertUtils.dp2px(45f)
        )
        gravity = Gravity.CENTER
        textSize = 13f
        text = "查看更多"
        setTypeface(null, Typeface.BOLD)
        setTextColor(ColorUtils.getColor(R.color.FF_666666))
    }
}